package common.controls
{
    import cn.flashk.controls.Alert;
    import cn.flashk.controls.Button;
    import cn.flashk.controls.events.AlertCloseEvent;

    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.utils.Timer;

    import mx.controls.Text;

    public class TimeAlert
    {
        private var _alert:Alert;

        private var _index:int;
        private var _lab:String;
        private var _time:Timer;
        private var _lesTime:int;

        private var _basLabel:String;

        /**
         *  创建一个倒计时Alert管理器
         * @param alert 要使用倒计时的alert
         * @param time 倒计时的时间，单位为秒
         * @param defaultBtnIndel 倒计时结束时默认要选取的按钮从1开始的索引
         *
         */
        public function TimeAlert(alert:Alert , time:uint , defaultBtnIndel:int = 1)
        {
            if (time == 0)
                return;
            _lesTime = time;
            _alert = alert;
            _index = defaultBtnIndel - 1;
            _alert.addEventListener ("close" , onclose);
            _basLabel = (_alert.buttons[_index] as Button).label;
            _time = new Timer (1000 , time);
            _time.addEventListener (TimerEvent.TIMER , ontimer);
            _time.addEventListener (TimerEvent.TIMER_COMPLETE , ontimeComplete);
            _time.start ();
        }

        private function ontimer(e:TimerEvent = null):void
        {
            if (e)
            {
                _lesTime -= 1;
            }

            (_alert.buttons[_index] as Button).label = _basLabel + "[" + _lesTime + "]";
        }

        private function ontimeComplete(e:TimerEvent):void
        {
            _alert.close (new AlertCloseEvent ("" , _index + 1 , ""));
        }

        private function onclose(e:Event):void
        {
            _alert.removeEventListener ("close" , onclose);
            _time.stop ();
            _time.removeEventListener (TimerEvent.TIMER , ontimer);
            _time.removeEventListener (TimerEvent.TIMER_COMPLETE , ontimeComplete);
            _time = null;
        }
    }
}
